package com.ysd.lis.service.bac.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import com.ysd.common.Result;
import com.ysd.lis.entity.SysUser;
import com.ysd.lis.entity.bac.*;
import com.ysd.lis.entity.lab.LabCriticalReport;
import com.ysd.lis.entity.lab.LabMaininfo;
import com.ysd.lis.mapper.bac.BacCultureMediumMapper;
import com.ysd.lis.mapper.bac.BacStainingResultMapper;
import com.ysd.lis.mapper.lab.LabCriticalReportMapper;
import com.ysd.lis.mapper.lab.LabMaininfoMapper;
import com.ysd.lis.request.Params;
import com.ysd.lis.service.SysUserService;
import com.ysd.lis.service.bac.BacCultrueInfoService;
import com.ysd.lis.service.bac.BacCultureCombinationService;
import com.ysd.lis.service.bac.BacPublisSecReportService;
import com.ysd.lis.service.bac.BacStainingResultService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * <p>
 * 染色结果 服务实现类
 * </p>
 *
 * @author cfz
 * @since 2024-03-27
 */
@Service
public class BacStainingResultServiceImpl extends ServiceImpl<BacStainingResultMapper, BacStainingResult> implements BacStainingResultService {
    @Autowired
    BacStainingResultMapper bacStainingResultMapper;

    @Autowired
    BacCultureCombinationService bacCultureCombinationService;

    @Autowired
    BacCultureMediumMapper bacCultureMediumMapper;

    @Autowired
    BacCultrueInfoService bacCultrueInfoService;

    @Autowired
    SysUserService sysUserService;

    @Autowired
    LabCriticalReportMapper labCriticalReportMapper;

    @Autowired
    LabMaininfoMapper labMaininfoMapper;

    @Autowired
    BacPublisSecReportService bacPublisSecReportService;


    @Override
    public Result findBacStainingResultList(BacStainingResult bacStainingResult) {
        List<BacStainingResult> list = findBacStainingResultArray(bacStainingResult);
        return Result.succ(1, "请求成功", list);
    }

    @Override
    public List<BacStainingResult> findBacStainingResultArray(BacStainingResult bacStainingResult) {
        MPJLambdaWrapper<BacStainingResult> queryWrapper = new MPJLambdaWrapper<>();
        queryWrapper.eq(BacStainingResult::getDelFlag, 0);
        //queryWrapper.eq(StringUtils.isNotBlank(bacStainingResult.getMaininfoId()), BacStainingResult::getMaininfoId, bacStainingResult.getMaininfoId());
        queryWrapper.eq(BacStainingResult::getRptGroup, bacStainingResult.getRptGroup());
        queryWrapper.eq(BacStainingResult::getSampleNo, bacStainingResult.getSampleNo());
        //queryWrapper.eq(BacStainingResult::getSampleda, bacStainingResult.getSampleda());
        Timestamp timestamp = new Timestamp(bacStainingResult.getSampleda().getTime());
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String formattedDate = sdf.format(timestamp);
        Timestamp startTime = Timestamp.valueOf(formattedDate + " 00:00:00");
        Timestamp endTime = Timestamp.valueOf(formattedDate + " 23:59:59");
        queryWrapper.ge(BacStainingResult::getSampleda, startTime);
        queryWrapper.le(BacStainingResult::getSampleda, endTime);

        queryWrapper.eq(StringUtils.isNotBlank(bacStainingResult.getRptGroup()), BacStainingResult::getRptGroup, bacStainingResult.getRptGroup());
        return bacStainingResultMapper.selectList(queryWrapper);
    }

    @Override
    public Result addBacStainingResult(BacStainingResult bacStainingResult) {
        int i = bacStainingResultMapper.insert(bacStainingResult);
        if (i > 0) {
            return Result.succ(1, "新增成功", bacStainingResult);
        }
        return Result.fail("新增失败");
    }

    @Override
    public Result deleteBacStainingResult(BacStainingResult bacStainingResult) {
        bacStainingResult.setDelFlag(1);
        int i = bacStainingResultMapper.updateById(bacStainingResult);
        //删除掉子级
        LambdaQueryWrapper<BacStainingResult> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(BacStainingResult::getParentId, bacStainingResult.getId());
        bacStainingResultMapper.delete(lambdaQueryWrapper);
        if (i > 0) {
            return Result.succ(1, "删除成功", bacStainingResult);
        }
        return Result.fail("删除失败");
    }

    @Override
    public Result updateBacStainingResult(BacStainingResult bacStainingResult) {
        int i = bacStainingResultMapper.updateById(bacStainingResult);
        if (i > 0) {
            /*查询是否已存在危急值，有：跳过不处理，无：添加一条数据*/
            /*MPJLambdaWrapper<LabCriticalReport> queryWrapper = new MPJLambdaWrapper<>();
            queryWrapper.eq(LabCriticalReport::getDelFlag, 0);
            queryWrapper.eq(LabCriticalReport::getRptGroup, bacStainingResult.getRptGroup());
            queryWrapper.eq(LabCriticalReport::getSampleNo, bacStainingResult.getSampleNo());
            Timestamp timestamp = new Timestamp(bacStainingResult.getSampleda().getTime());
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            String formattedDate = sdf.format(timestamp);
            Timestamp startTime = Timestamp.valueOf(formattedDate + " 00:00:00");
            Timestamp endTime = Timestamp.valueOf(formattedDate + " 23:59:59");
            queryWrapper.ge(LabCriticalReport::getSampleda, startTime);
            queryWrapper.le(LabCriticalReport::getSampleda, endTime);
            queryWrapper.eq(LabCriticalReport::getResultId, bacStainingResult.getId());

            List<LabCriticalReport> list = labCriticalReportMapper.selectList(queryWrapper);*/
//            if (list.isEmpty()) {
//                /*查询出检验主记录*/
//                MPJLambdaWrapper<LabMaininfo> mainQueryWrapper = new MPJLambdaWrapper<>();
//                mainQueryWrapper.eq(LabMaininfo::getDelFlag, 0);
//                sdf = new SimpleDateFormat("yyyy-MM-dd");
//                formattedDate = sdf.format(timestamp);
//                startTime = Timestamp.valueOf(formattedDate + " 00:00:00");
//                endTime = Timestamp.valueOf(formattedDate + " 23:59:59");
//                mainQueryWrapper.ge(LabMaininfo::getSampleda, startTime);
//                mainQueryWrapper.le(LabMaininfo::getSampleda, endTime);
//                mainQueryWrapper.eq(LabMaininfo::getRptGroup, bacStainingResult.getRptGroup());
//                mainQueryWrapper.eq(LabMaininfo::getSampleNo, bacStainingResult.getSampleNo());
//
//                List<LabMaininfo> miList = labMaininfoMapper.selectList(mainQueryWrapper);
//
//                LabMaininfo miEntry = miList.isEmpty() ? null : miList.get(0);
//
//                /*添加危机表*/
//                LabCriticalReport crEntry = new LabCriticalReport();
//                crEntry.setRptGroup(bacStainingResult.getRptGroup());
//                crEntry.setSampleda(bacStainingResult.getSampleda());
//                crEntry.setSampleNo(bacStainingResult.getSampleNo());
//                crEntry.setResultId(bacStainingResult.getId());
//                crEntry.setIsReport(0);
//                crEntry.setNotifyPerson(BeanUtil.isNotEmpty(miEntry) ? miEntry.getReqDoctor() : "");
//                crEntry.setReportPerson(bacStainingResult.getCreator());
//                crEntry.setRequestNo(BeanUtil.isNotEmpty(miEntry) ? miEntry.getReqNo() : "");
//                crEntry.setReportTime(new Timestamp(new Date().getTime()));
//                crEntry.setPatNo(BeanUtil.isNotEmpty(miEntry) ? miEntry.getPatNo() : "");
//                crEntry.setCriticalType(2);
//
//                int inum = labCriticalReportMapper.insert(crEntry);
//
//                /*更新检验记录*/
//                if (inum > 0 && BeanUtil.isNotEmpty(miEntry)) {
//                    miEntry.setIsAlarm(1);
//                    labMaininfoMapper.updateById(miEntry);
//                }
//            }


            /*是否发布二级报告*/
            if (BeanUtil.isNotEmpty(bacStainingResult.getIsPushSecReport()) && bacStainingResult.getIsPushSecReport().equals(1)) {
                LambdaQueryWrapper<BacPublisSecReport> lambdaQueryWrapper = new LambdaQueryWrapper<>();
                Timestamp timestamp = new Timestamp(bacStainingResult.getSampleda().getTime());
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                String formattedDate = sdf.format(timestamp);
                Timestamp startTime = Timestamp.valueOf(formattedDate + " 00:00:00");
                Timestamp endTime = Timestamp.valueOf(formattedDate + " 23:59:59");
                lambdaQueryWrapper.ge(BacPublisSecReport::getSampleda, startTime);
                lambdaQueryWrapper.le(BacPublisSecReport::getSampleda, endTime);
                lambdaQueryWrapper.eq(BacPublisSecReport::getRptGroup, bacStainingResult.getRptGroup());
                lambdaQueryWrapper.eq(BacPublisSecReport::getSampleNo, bacStainingResult.getSampleNo());
                lambdaQueryWrapper.eq(BacPublisSecReport::getTestFlowNo, bacStainingResult.getTestFlowNo());
                lambdaQueryWrapper.eq(BacPublisSecReport::getTestNodeNo, bacStainingResult.getTestNodeNo());
                lambdaQueryWrapper.eq(BacPublisSecReport::getStrainNo, bacStainingResult.getStrainNo());
                bacPublisSecReportService.remove(lambdaQueryWrapper);

                /*插入二级报告*/
                BacPublisSecReport secReportEntry = new BacPublisSecReport();
                secReportEntry.setRptGroup(bacStainingResult.getRptGroup());
                secReportEntry.setSampleda(bacStainingResult.getSampleda());
                secReportEntry.setSampleNo(bacStainingResult.getSampleNo());
                secReportEntry.setTestFlowNo(bacStainingResult.getTestFlowNo());
                secReportEntry.setTestNodeNo(bacStainingResult.getTestNodeNo());
                secReportEntry.setStrainNo(bacStainingResult.getStrainNo());
                secReportEntry.setStainingResulId(bacStainingResult.getId());

                bacPublisSecReportService.save(secReportEntry);
            }

            return Result.succ(1, "更新成功", bacStainingResult);
        }
        return Result.fail("更新失败");
    }

    @Override
    public Result findBacStainingResultListByStrain(Params params) {
        MPJLambdaWrapper<BacStainingResult> queryWrapper = new MPJLambdaWrapper<>();
        queryWrapper.selectAll(BacStainingResult.class).selectAs("b", SysUser::getRealname, BacStainingResult::getUserName).selectAs("C", BacCultureMedium::getName, BacStainingResult::getCulMediumNa).leftJoin(SysUser.class, "b", SysUser::getId, BacStainingResult::getEditor).leftJoin(BacCultureMedium.class, "c", p -> p.eq(BacCultureMedium::getCode, BacStainingResult::getCulMediumNo).eq(BacCultureMedium::getDelFlag, 0));
        queryWrapper.eq(BacStainingResult::getDelFlag, 0);
        queryWrapper.eq(BacStainingResult::getRptGroup, params.getRptGroup());
        queryWrapper.eq(BacStainingResult::getSampleNo, params.getSampleNo());
        //queryWrapper.eq(BacStainingResult::getDelFlag, 0);
        Timestamp timestamp = new Timestamp(params.getSampleda().getTime());
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String formattedDate = sdf.format(timestamp);
        Timestamp startTime = Timestamp.valueOf(formattedDate + " 00:00:00");
        Timestamp endTime = Timestamp.valueOf(formattedDate + " 23:59:59");
        queryWrapper.ge(BacStainingResult::getSampleda, startTime);
        queryWrapper.le(BacStainingResult::getSampleda, endTime);
        queryWrapper.eq(BacStainingResult::getStrainNo, params.getStrainId());
        queryWrapper.orderByDesc(BacStainingResult::getId);
        queryWrapper.orderByDesc(BacStainingResult::getEditTime);
        List<BacStainingResult> bacStainingResultList = bacStainingResultMapper.selectList(queryWrapper);

//        for (BacStainingResult bacStainingResult : bacStainingResultList) {
//            SysUser sysUser = sysUserService.getBaseMapper().selectById(bacStainingResult.getEditor());
//            bacStainingResult.setUserName(sysUser == null ? "" : sysUser.getRealname());
//        }
        return Result.fail(1, "查询成功", bacStainingResultList);
    }

    @Transactional
    @Override
    public Result batchAddBacStainingResult(List<BacStainingResult> bacStainingResultList) {

        for (BacStainingResult stainingResult : bacStainingResultList) {
            boolean b = this.save(stainingResult);
            if (!b) {
                return Result.fail(400, "添加失败", "");
            }
            //String id = stainingResult.getId();
//            if (!Objects.equals(stainingResult.getHandleType(), "0")) {
//                MPJLambdaWrapper<BacCultureMedium> mpjLambdaWrapper = new MPJLambdaWrapper<>();
//                mpjLambdaWrapper.selectAll(BacCultureMedium.class);
//                mpjLambdaWrapper.leftJoin(BacCultureCombinaRel.class, p -> p.eq(BacCultureCombinaRel::getCulMediumNo, BacCultureMedium::getCode).eq(BacCultureCombinaRel::getDelFlag, 0));//BacCultureCombinaRel::getCultrueId, BacCultureMedium::getId);
//                mpjLambdaWrapper.eq(BacCultureMedium::getDelFlag, 0);
//                if (com.baomidou.mybatisplus.core.toolkit.StringUtils.isNotBlank(stainingResult.getCulCombinaNo())) {
//                    mpjLambdaWrapper.eq(BacCultureCombinaRel::getCulCombinaNo, stainingResult.getCulCombinaNo());
//                }
//                List<BacCultureMedium> bacCultureMediumList = bacCultureMediumMapper.selectList(mpjLambdaWrapper);
//
//                for (BacCultureMedium cultureMedium : bacCultureMediumList) {
//                    BacCultrueInfo bacCultrueInfo = new BacCultrueInfo();
//                    //bacCultrueInfo.setMaininfoId(stainingResult.getMaininfoId());
//                    bacCultrueInfo.setSampleda(stainingResult.getSampleda());
//                    bacCultrueInfo.setSampleNo(stainingResult.getSampleNo());
//                    bacCultrueInfo.setRptGroup(stainingResult.getRptGroup());
//                    bacCultrueInfo.setStrainNo(stainingResult.getStrainNo());
//                    bacCultrueInfo.setCulMediumNo(cultureMedium.getCode());
//                    bacCultrueInfo.setTestFlowNo(stainingResult.getTestFlowNo());
//                    bacCultrueInfo.setTestNodeNo(stainingResult.getTestNodeNo());
//                    //bacCultrueInfo.setStainingResultId(stainingResult.getId());
//                    bacCultrueInfo.setIsolateNum(stainingResult.getIsolateNum());
//                    //bacCultrueInfo.setGermNo(stainingResult.);
//
//                    if (Objects.equals(stainingResult.getHandleType(), "1")) {
//                        bacCultrueInfo.setCultrueNa(cultureMedium.getName() + "(纯)");
//                    } else {
//                        bacCultrueInfo.setCultrueNa(cultureMedium.getName() + "(种)");
//                    }
//
//                    bacCultrueInfoService.save(bacCultrueInfo);
//                }
//            }
        }
        return Result.succ(1, "添加成功", null);

    }

    @Override
    public Result findBacStainingResultListBySampleNo(BacStainingResult params) {
        MPJLambdaWrapper<BacStainingResult> queryWrapper = new MPJLambdaWrapper<>();
        queryWrapper.selectAll(BacStainingResult.class).selectAs("b", SysUser::getRealname, BacStainingResult::getUserName).selectAs("C", BacCultureMedium::getName, BacStainingResult::getCulMediumNa).leftJoin(SysUser.class, "b", SysUser::getId, BacStainingResult::getEditor).leftJoin(BacCultureMedium.class, "c", p -> p.eq(BacCultureMedium::getCode, BacStainingResult::getCulMediumNo).eq(BacCultureMedium::getDelFlag, 0));
        queryWrapper.eq(BacStainingResult::getDelFlag, 0);
        queryWrapper.eq(BacStainingResult::getRptGroup, params.getRptGroup());
        queryWrapper.eq(BacStainingResult::getSampleNo, params.getSampleNo());
        //queryWrapper.eq(BacStainingResult::getDelFlag, 0);
        Timestamp timestamp = new Timestamp(params.getSampleda().getTime());
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String formattedDate = sdf.format(timestamp);
        Timestamp startTime = Timestamp.valueOf(formattedDate + " 00:00:00");
        Timestamp endTime = Timestamp.valueOf(formattedDate + " 23:59:59");
        queryWrapper.ge(BacStainingResult::getSampleda, startTime);
        queryWrapper.le(BacStainingResult::getSampleda, endTime);
        queryWrapper.isNull(BacStainingResult::getStrainNo);
        queryWrapper.eq(Objects.nonNull(params.getIsPushSecReport()),BacStainingResult::getIsPushSecReport, params.getIsPushSecReport());
        queryWrapper.orderByDesc(BacStainingResult::getId);
        queryWrapper.orderByDesc(BacStainingResult::getEditTime);
        List<BacStainingResult> bacStainingResultList = bacStainingResultMapper.selectList(queryWrapper);

        return Result.fail(1, "查询成功", bacStainingResultList);
    }
}
